#include "usermanagemenpage.h"
#include "ui_usermanagemenpage.h"
#include "dialogs/modifyuserdialog.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QInputDialog>

UserManagementPage::UserManagementPage(QWidget *parent) :
    MyWidget(parent),
    ui(new Ui::UserManagementPage)
{
    ui->setupUi(this);

    loadUserData();

    connect(ui->tableWidgetUsers, &QTableWidget::itemSelectionChanged, this, &UserManagementPage::on_tableWidgetUsers_itemSelectionChanged);
}

UserManagementPage::~UserManagementPage()
{
    delete ui;
}

void UserManagementPage::loadUserData()
{
    QList<QVariantList> users = SqlHelper::getInstance().queryUsers();

    ui->tableWidgetUsers->clearContents();
    ui->tableWidgetUsers->setRowCount(0);

    ui->tableWidgetUsers->setColumnCount(3);
    ui->tableWidgetUsers->setHorizontalHeaderLabels(QStringList() << "Username" << "Password" << "Role");
    ui->tableWidgetUsers->horizontalHeader()->setStretchLastSection(true); // 占据整个宽度

    for (const QVariantList &user : users)
    {
        int row = ui->tableWidgetUsers->rowCount();
        ui->tableWidgetUsers->insertRow(row);

        ui->tableWidgetUsers->setItem(row, 0, new QTableWidgetItem(user[0].toString()));  // username
        ui->tableWidgetUsers->setItem(row, 1, new QTableWidgetItem(user[1].toString()));  // password
        ui->tableWidgetUsers->setItem(row, 2, new QTableWidgetItem(user[2].toString()));  // role
    }
}

void UserManagementPage::on_tableWidgetUsers_itemSelectionChanged()
{
    // 获取当前选中的行
    selectedRow = ui->tableWidgetUsers->currentRow();
}

void UserManagementPage::on_pushButtonModify_clicked()
{
    if (selectedRow == -1) {
        QMessageBox::warning(this, "警告", "请选中一行用户数据！");
        return;
    }

    // 获取选中行的数据
    QString username = ui->tableWidgetUsers->item(selectedRow, 0)->text();
    QString password = ui->tableWidgetUsers->item(selectedRow, 1)->text();
    QString role = ui->tableWidgetUsers->item(selectedRow, 2)->text();

    // 创建修改用户对话框并传递数据
    ModifyUserDialog dialog(username, password, role, this);

    if (dialog.exec() == QDialog::Accepted) {
        // 获取用户输入的修改数据
        QString newUsername = dialog.getUsername();
        QString newPassword = dialog.getPassword();
        QString newRole = dialog.getRole();

        bool success = SqlHelper::getInstance().updateUser(username, newUsername, newPassword, newRole);

        if (success) {
            // 更新成功后重新加载数据
            loadUserData();
            QMessageBox::information(this, "成功", "用户信息已更新！");
        } else {
            QMessageBox::critical(this, "错误", "更新用户信息失败！");
        }
    }
}

void UserManagementPage::on_pushButtonDelete_clicked()
{
    if (selectedRow == -1) {
        QMessageBox::warning(this, "警告", "请选中一行用户数据！");
        return;
    }

    // 获取选中行的用户名
    QString username = ui->tableWidgetUsers->item(selectedRow, 0)->text();

    // 弹出确认删除对话框
    QMessageBox::StandardButton reply = QMessageBox::question(this, "确认删除", "确定要删除用户 " + username + " 吗？",
                                                                QMessageBox::Yes | QMessageBox::No);

    if (reply == QMessageBox::Yes) {

        if (SqlHelper::getInstance().deleteUser(username)) {            
            QMessageBox::information(this, "成功", "用户 " + username + " 已删除！");
            loadUserData();
        }
        else {
            QMessageBox::critical(this, "错误", "删除用户失败！");
        }
    }
}

void UserManagementPage::on_pushButtonInsert_clicked()
{
    ModifyUserDialog dialog("", "", "用户", this);

    if (dialog.exec() == QDialog::Accepted) {

        QString username = dialog.getUsername();
        QString password = dialog.getPassword();
        QString role = dialog.getRole();

        bool ok;
        QString studentId = QInputDialog::getText(this, "输入学生信息", "输入学号：", QLineEdit::Normal, "", &ok);
        if (!ok || studentId.isEmpty()) return;
        QString dormitoryAddr = QInputDialog::getText(this, "输入学生信息", "输入宿舍：", QLineEdit::Normal, "", &ok);
        if (!ok || dormitoryAddr.isEmpty()) return;

        if (SqlHelper::getInstance().insertUser(username, password, role)
         && SqlHelper::getInstance().insertStudent(username, studentId, dormitoryAddr)) {

            QMessageBox::information(this, "成功", "新增用户成功！");
            loadUserData();
        }
        else {
            QMessageBox::critical(this, "错误", "新增用户失败！");
        }
    }
}
